// pages/evaluate/evaluate.js
const API = require('../../utils/api')
const pathUrl = require('../../utils/common.js')

Page({
  data: {
    testVideos: [],
    searchKey: '',
    currentFilter: '全部',
    currentCategory: '全部',
    filters: [
      { id: '全部', name: '全部' },
      { id: '初级', name: '初级' },
      { id: '中级', name: '中级' },
      { id: '高级', name: '高级' }
    ],
    categories: [
      { id: '全部', name: '全部' },
      { id: '技术测试', name: '技术测试' },
      { id: '体能测试', name: '体能测试' },
      { id: '战术测试', name: '战术测试' },
      { id: '比赛测试', name: '比赛测试' }
    ],
    page: 1,
    hasMore: true,
    loading: false
  },
  onLoad(options) {
    this.loadTestVideos()
  },

  onShow() {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadTestVideos(true)
    wx.stopPullDownRefresh()
  },

  /**
   * 加载测试视频列表
   */
  async loadTestVideos(reset = true) {
    if (reset) {
      this.setData({ page: 1, hasMore: true })
    }
    if (!this.data.hasMore && !reset) return
    this.setData({ loading: true })
    try {
      let queryForm = {difficulty:this.data.currentFilter=='全部'?'':this.data.currentFilter,testType:this.data.currentCategory=='全部'?'':this.data.currentCategory,title:this.data.searchKey,pageNum:this.data.page,pageSize:5}
      const newVideos = await API.evaluateVideoList(queryForm)
      for(let i=0;i<newVideos.records.length;i++){
        newVideos.records[i].videoUrl = pathUrl+newVideos.records[i].videoUrl ;
      }
      this.setData({
        testVideos: reset ? newVideos.records : [...this.data.testVideos, ...newVideos.records],
        hasMore: newVideos.records && newVideos.records.length >= 5,
        loading: false
      })
    } catch (error) {
      console.error('加载测试视频失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },
  onSearch(e) {
    this.setData({ searchKey: e.detail.value })
    this.loadTestVideos()
  },
  switchFilter(e) {
    const filter = e.currentTarget.dataset.id
    this.setData({ currentFilter: filter })
    this.loadTestVideos()
  },
  switchCategory(e) {
    const category = e.currentTarget.dataset.category
    this.setData({ currentCategory: category })
    this.loadTestVideos()
  },

  goToTestVideoDetail(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/video-player/video-player?url=${item.videoUrl}`
    })
  },

  loadMore() {
    if (!this.data.loading && this.data.hasMore) {
      this.setData({ page: this.data.page + 1 })
      this.loadTestVideos(false)
    }
  },

  onShareAppMessage() {
    return {
      title: '网球技术测试视频',
      path: '/pages/evaluate/evaluate',
      imageUrl: '/images/share-video.jpg'
    }
  },

  onReachBottom() {
    this.loadMore()
  }
})